﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Test
{
    public class HttpUtil
    {
        public string Post(string apiPath, string postData, WebHeaderCollection collection = null, string contenttype = "application/json;charset=utf-8")
        {
            System.GC.Collect();//垃圾回收，回收没有正常关闭的http连接
            try
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; };
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


                HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(apiPath);
                httpRequest.Method = "POST";
                httpRequest.Referer = null;
                httpRequest.AllowAutoRedirect = true;
                httpRequest.ContentType = contenttype;
                httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                httpRequest.Accept = "*/*";

                if (collection != null)
                {
                    for (int i = 0; i < collection.Count; i++)
                    {
                        for (int j = 0; j < collection.GetValues(i).Length; j++)
                        {
                            httpRequest.Headers.Add(collection.Keys[i], collection.GetValues(i)[j]);
                        }
                    }
                }
                var data = Encoding.UTF8.GetBytes(postData);
                httpRequest.ContentLength = data.Length;
                //往服务器写入数据
                var reqStream = httpRequest.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
                string result = string.Empty;
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
                {
                    result = streamReader.ReadToEnd();
                }
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
